<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>localStorage</title>
</head>
<body>
    <!-- 浏览器关闭后仍会存在 -->
  <h2>localstorage</h2>
  <button onclick="saveData()">点我保存一个数据</button>
  <button onclick="readData()">点我读取一个数据</button>
  <button onclick="deleteData()">点我删除一个数据</button>
  <button onclick="removeAllData()">清空所有数据</button>
</body>
<script type="text/javascript">
    let p = {name: '张三',age: '21'}
    //添加数据
    function saveData(){
        localStorage.setItem('msg', 'hello!');
        localStorage.setItem('msg1', 666); //存的只要不是字符串类型就会被转换为字符串
        //对象转换为字符串
        localStorage.setItem('person',JSON.stringify(p))
    }
    // 读取数据
    function readData(){
        console.log(localStorage.getItem('msg'))
        //读取对象需要JSON转换一下
        const person = localStorage.getItem('person')
        console.log(JSON.parse(person));
        //console.log(localStorage.getItem('text')); //注意：读取不存在的数据就是null Json.parse(null)仍然是null
    }
    // 删除数据
    function deleteData(){
        localStorage.removeItem('msg1');
    }
    //删除所有数据
    function removeAllData(){
       localStorage.clear();
    }
</script>
</html>
